﻿using PLCWpfTest.Common.Extensions;
using System.Threading.Tasks;
using YWM;
using YWM.Common.Exceptions;
using YWM.Dto;

namespace PLCWpfTest.Common
{
    public abstract class ManagementViewModel : BaseViewModel
    {
        private int _current = 1;
        public virtual int Current
        {
            get { return _current; }
            set { SetProperty(ref _current, value); }
        }

        /// <summary>
        /// 删除命令
        /// </summary>
        public AsyncRelayCommand<(IEntityDto, DatabaseMethod)> DeleteCommand { get; set; }

        public ManagementViewModel()
        {
            DeleteCommand = YApp.Resolve<AsyncRelayCommand<(IEntityDto, DatabaseMethod)>>();
            DeleteCommand.BeforeExecute += DeleteCommand_BeforeExecute;
            DeleteCommand.Executing += DeleteCommand_Executing;
            DeleteCommand.UnexecutedFriendlyException += DeleteCommand_UnexecutedFriendlyException;
        }

        /// <summary>
        /// 删除命令执行前事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        protected virtual bool DeleteCommand_BeforeExecute(object arg)
        {
            return true;
        }

        /// <summary>
        /// 删除命令执行中事件
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task<(IEntityDto, DatabaseMethod)> DeleteCommand_Executing(object parameter)
        {
            IEntityDto entityDto = await DeleteAsync(parameter);
            return (entityDto, DatabaseMethod.Delete);
        }

        /// <summary>
        /// 删除异步抽象方法
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        protected virtual Task<IEntityDto> DeleteAsync(object parameter)
        {
            return Task.FromResult(default(IEntityDto));
        }

        /// <summary>
        /// 删除命令未执行的友好异常事件
        /// </summary>
        /// <param name="ex"></param>
        private void DeleteCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            DeleteCommand.ShowError(ex.Message);
        }
    }
}
